<template>
  <div class="login-page">
    <div class="login-left">
      <div class="login-title">精品甄选</div>
      <el-card class="login-card">
        <el-tabs v-model="activeTab" class="mb-4">
          <el-tab-pane label="登录" name="login"></el-tab-pane>
          <el-tab-pane label="注册" name="register"></el-tab-pane>
        </el-tabs>
        <!-- 登录表单 -->
        <el-form v-if="activeTab === 'login'" :model="loginForm" :rules="loginRules" ref="loginFormRef" label-width="80px">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" placeholder="用户名" prefix-icon="el-icon-user" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="密码"
                prefix-icon="el-icon-lock"
                @keyup.enter="handleLogin"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="loginLoading" @click="handleLogin" class="login-btn">
              登录
            </el-button>
          </el-form-item>
        </el-form>
        <!-- 注册表单 -->
        <el-form v-if="activeTab === 'register'" :model="registerForm" :rules="registerRules" ref="registerFormRef" label-width="80px">
          <el-form-item prop="username">
            <el-input v-model="registerForm.username" placeholder="用户名" prefix-icon="el-icon-user" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
                v-model="registerForm.password"
                type="password"
                placeholder="密码（至少6位）"
                prefix-icon="el-icon-lock"
            />
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="确认密码"
                prefix-icon="el-icon-lock"
            />
          </el-form-item>
          <el-form-item prop="phone">
            <el-input v-model="registerForm.phone" placeholder="手机号" prefix-icon="el-icon-phone" />
          </el-form-item>
          <el-form-item prop="code">
            <el-row :gutter="10">
              <el-col :span="16">
                <el-input v-model="registerForm.code" placeholder="验证码" prefix-icon="el-icon-key" />
              </el-col>
              <el-col :span="8">
                <el-button
                    :disabled="sendingCode || countdown > 0"
                    :loading="sendingCode"
                    @click="sendVerificationCode"
                    style="width: 100%"
                >
                  {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="registerLoading" @click="handleRegister" class="register-btn">
              注册
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div class="login-right">
      <div class="login-bg-img"></div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from "@/router/index.js";

export default {
  setup() {
    // 标签页状态
    const activeTab = ref('login')

    // 登录表单状态
    const loginForm = reactive({
      username: '',
      password: ''
    })
    const loginFormRef = ref(null)
    const loginLoading = ref(false)
    const loginMessage = ref('')

    // 注册表单状态
    const registerForm = reactive({
      username: '',
      password: '',
      confirmPassword: '',
      phone: '',
      code: '' // 验证码字段
    })
    const registerFormRef = ref(null)
    const registerLoading = ref(false)
    const registerMessage = ref('')
    const registerSuccess = ref(false)

    // 验证码相关状态
    const sendingCode = ref(false)
    const countdown = ref(0)
    let timer = null

    // 登录表单验证规则
    const loginRules = reactive({
      username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
      password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
    })

    // 注册表单验证规则
    const registerRules = reactive({
      username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        { validator: (rule, value, callback) => {
            if (value !== registerForm.password) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          }, trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
      ],
      code: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { min: 6, max: 6, message: '验证码为6位数字', trigger: 'blur' },
        { pattern: /^\d{6}$/, message: '验证码格式不正确', trigger: 'blur' }
      ]
    })

    // 登录处理
    const handleLogin = async () => {
      if (loginFormRef.value) {
        try {
          await loginFormRef.value.validate()
        } catch (error) {
          console.log('登录表单验证失败', error)
          return
        }
      }
      loginLoading.value = true
      loginMessage.value = ''
      try {
        const response = await axios.post('/api/user/user/login', {
          username: loginForm.username,
          password: loginForm.password
        })
        if (response.data === '登录成功') {
          localStorage.setItem('token', 'your-token-here')
          ElMessage.success('登录成功')
          // window.location.href = '/admin/dashboard'
          router.push('/main3')
        } else {
          ElMessage.error(response.data || '用户名或密码错误')
        }
      } catch (error) {
        console.error('登录请求失败', error)
        ElMessage.error('登录失败，请稍后再试')
      } finally {
        loginLoading.value = false
      }
    }

    // 发送验证码
    const sendVerificationCode = async () => {
      // 验证手机号格式
      if (!registerForm.phone) {
        registerMessage.value = '请输入手机号'
        return
      }
      const phonePattern = /^1[3-9]\d{9}$/
      if (!phonePattern.test(registerForm.phone)) {
        registerMessage.value = '手机号格式不正确'
        return
      }
      sendingCode.value = true
      registerMessage.value = ''
      try {
        // 对接后端验证码接口，params方式传递手机号
        const response = await axios.get('/api/user/yzm/get', {
          params: { phone: registerForm.phone }
        })
        // 后端Result对象一般有success和message字段
        if (response.data && response.data.success) {
          registerMessage.value = '验证码已发送，请注意查收'
          startCountdown()
        } else {
          registerMessage.value = (response.data && response.data.message) || '验证码发送失败'
        }
      } catch (error) {
        console.error('发送验证码失败', error)
        registerMessage.value = '验证码发送失败，请稍后再试'
      } finally {
        sendingCode.value = false
      }
    }

    // 倒计时逻辑
    const startCountdown = () => {
      countdown.value = 60
      timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    }

    // 生命周期钩子
    onMounted(() => {
      // 组件挂载时初始化
    })

    onUnmounted(() => {
      if (timer) {
        clearInterval(timer)
      }
    })

    // 注册处理
    const handleRegister = async () => {
      if (registerFormRef.value) {
        try {
          await registerFormRef.value.validate()
        } catch (error) {
          console.log('注册表单验证失败', error)
          return
        }
      }
      registerLoading.value = true
      registerMessage.value = ''
      try {
        const response = await axios.post('/api/user/user/register', {
          username: registerForm.username,
          password: registerForm.password,
          phone: registerForm.phone,
          code: registerForm.code
        })
        const result = response.data
        if (result.success) {
          ElMessage.success(result.message || '注册成功')
          setTimeout(() => {
            activeTab.value = 'login'
          }, 1500)
        } else {
          ElMessage.error(result.message || '注册失败')
        }
      } catch (error) {
        console.error('注册请求失败', error)
        ElMessage.error('注册失败，请稍后再试')
      } finally {
        registerLoading.value = false
      }
    }

    return {
      activeTab,
      loginForm,
      loginRules,
      loginFormRef,
      loginLoading,
      loginMessage,
      handleLogin,
      registerForm,
      registerRules,
      registerFormRef,
      registerLoading,
      registerMessage,
      registerSuccess,
      handleRegister,
      sendingCode,
      countdown,
      sendVerificationCode
    }
  }
}
</script>
<style scoped>
.login-page {
  display: flex;
  height: 100vh;
  background: #f6f6fa;
}
.login-left {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: #fff;
  position: relative;
  z-index: 2;
  box-shadow: 0 0 24px 0 rgba(128,0,255,0.04);
}
.login-title {
  font-size: 32px;
  font-weight: bold;
  color: #f5e752;
  margin-bottom: 32px;
  letter-spacing: 4px;
  text-align: center;
}
.login-card {
  width: 380px;
  border-radius: 18px;
  box-shadow: 0 8px 32px 0 rgba(128, 0, 255, 0.08);
  background: rgba(255,255,255,0.98);
  border: none;
  padding-top: 18px;
}
.el-tabs__item.is-active {
  color: #f5e752 !important;
}
.el-tabs__active-bar {
  background: #f5e752 !important;
}
.el-input__wrapper {
  border-radius: 8px !important;
  border: 1px solid #f5e752 !important;
}
.el-input__inner:focus {
  border-color: #f5e752 !important;
}
.el-form-item__label {
  color: #f5e752 !important;
}
.el-button.login-btn, .el-button.register-btn, .el-button[type="primary"] {
  width: 100%;
  height: 44px;
  font-size: 18px;
  border-radius: 22px;
  background: linear-gradient(90deg, #efdfa0 0%, #f5e752 100%);
  color: #fff;
  border: none;
  font-weight: bold;
  letter-spacing: 1px;
  transition: background 0.3s;
}
.el-button.login-btn:hover, .el-button.register-btn:hover, .el-button[type="primary"]:hover {
  background: linear-gradient(90deg, #f5e752 0%, #efdfa0 100%);
}
.login-right {
  flex: 1.2;
  position: relative;
  overflow: hidden;
  background: transparent;
  display: flex;
  align-items: stretch;
}
.login-bg-img {
  width: 100%;
  height: 100%;
  background: url('@/img/4.png') no-repeat center center;
  background-size: cover;
  /* 波浪/弧形遮罩效果 */
  clip-path: ellipse(80% 100% at 100% 50%);
}
@media (max-width: 900px) {
  .login-right {
    display: none;
  }
  .login-left {
    flex: 1 1 100%;
  }
}
</style>